package com.rlax.framework.plugin.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import com.rlax.framework.common.Consts;
import com.rlax.framework.common.Status;
import com.rlax.web.model.Res4s;

/**
 * 让 shiro 基于 url 拦截
 * 主要 数据库中也用url 保存权限
 * 
 * @author Rlax
 *
 */
public class ShiroInterceptor4s implements Interceptor {
	/**
	 * 获取全部 需要控制的权限
	 */
	private static List<String> urls;
	private static List<Res4s> resList;
	
	public static void updateUrls() {
		urls = Res4s.dao.findUrlByOnUse();
		resList = Res4s.dao.findByStatus(Status.COMMON_USE);
	}

	public static List<String> getUrls() {
		return urls;
	}

	public static List<Res4s> getResList() {
		return resList;
	}

	public void intercept(Invocation ai) {
		if (urls == null) updateUrls();

		String url = ai.getActionKey();
		boolean falg = SecurityUtils.getSubject() != null && SecurityUtils.getSubject().isPermitted(url);
		try {
			if (urls.contains(url) && !falg) ai.getController().renderError(403);

			// 菜单定位
			String funcTag = ai.getController().getPara(Consts.FUNC_TAG);
			if (StrKit.notBlank(funcTag)) {
				ai.getController().setSessionAttr(Consts.FUNC_TAG, funcTag);
			}
		} catch (Exception e) {
			ai.getController().renderError(403);
		}

		ai.invoke();

	}

}
